﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;
using FrameworkManapro.BusinessModel;
using FrameworkManapro.WebUI;
using GMAC.ReportingSystem.Business.Entities;

namespace GMAC.ReportingSystem.DataAccess
{
    public class UserDataAccess : BaseDataAccess<Business.Entities.User>
    {
        public override GMAC.ReportingSystem.Business.Entities.User Get(object id)
        {
            ArrayList parameters = new ArrayList() { id };
            DataTable dt = DataAccessComponent.ExecuteSelect("procUsersByIdSelect", parameters);
            if (dt != null && dt.Rows.Count > 0)
                return ReadRow(dt.Rows[0]);
            return null;
        }



        public UserCollection GetList()
        {
            DataTable dt = DataAccessComponent.ExecuteSelect("procUserSelect", null);
            return ReadTable(dt) as UserCollection;
        }

        protected override GMAC.ReportingSystem.Business.Entities.User ReadRow(System.Data.DataRow row)
        {
            User user = null;
            if (row != null)
            {
                try
                {
                    user = new User();
                    user.UserID = (int)row["UsersID"];
                    user.IdentificationNumber = Convert.ToInt32(row["IdentificationNumber"]);
                    user.Name = row["UsersName"].ToString();
                    user.LastName = (row["UsersLastName"] != System.DBNull.Value ? row["UsersLastName"].ToString() : string.Empty);
                    user.Department = row["UsersDepartment"].ToString();
                    user.Description = row["UsersDescription"].ToString();
                    user.Status = (bool)row["UsersStatus"];
                    user.Email = row["UsersEmail"].ToString();
                    user.Login = row["UsersLogin"].ToString();
                    user.Role = new Role();
                    {
                        user.Role.RoleID = (int)row["RoleID"];
                        user.Role.Name = row["RoleName"].ToString();
                    }

                }
                catch (Exception ex)
                {
                    throw;
                }
            }
            return user;
        }

        protected override List<GMAC.ReportingSystem.Business.Entities.User> ReadTable(System.Data.DataTable table)
        {
            try
            {
                UserCollection users = new UserCollection();
                User user;
                if (table != null && table.Rows.Count > 0)
                {
                    foreach (DataRow row in table.Rows)
                    {
                        user = ReadRow(row);
                        if (user != null)
                        {
                            users.Add(user);
                        }
                    }
                }
                return users;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public Business.Entities.User GetByLogin(string login)
        {
            Business.Entities.User loggedUser = null;
            ArrayList parameters = new ArrayList() { login };
            DataTable result = DataAccessComponent.ExecuteSelect("procUsersByLoginSelect", parameters);

            if (result != null && result.Rows.Count > 0)
            {
                DataRow row = result.Rows[0];
                loggedUser = ReadRow(row);
                // TODO: Verificar nombre de columna
                loggedUser.Password = row["UsersPassword"].ToString();
                loggedUser.MustChangePassword = (bool)row["ChangePassword"];
                loggedUser.LoginAttempts = (byte)row["LoginAttempts"];
            }

            return loggedUser;
        }

        /// <summary>
        /// Created by:   Michelle A. González A.
        /// Date:         04/08/2010
        /// Description:  Checks if there exists a user with the same login passed as a parameter.
        /// </summary>
        public Business.Entities.User GetByLoginRepeat(string login, string userId)
        {
            Business.Entities.User loggedUser = null;
            ArrayList parameters = new ArrayList() { login, userId };
            DataTable result = DataAccessComponent.ExecuteSelect("procUsersByLoginRepeatSelect", parameters);

            if (result != null && result.Rows.Count > 0)
            {
                DataRow row = result.Rows[0];
                loggedUser = ReadRow(row);
                // TODO: Verificar nombre de columna
                loggedUser.Password = row["UsersPassword"].ToString();
                loggedUser.MustChangePassword = (bool)row["ChangePassword"];
                loggedUser.LoginAttempts = (byte)row["LoginAttempts"];
            }

            return loggedUser;
        }

        public UserCollection Search(string userName, int? roleId, int? identificationNumber, string login, PagingDetails paging)
        {
            //ArrayList parameters = new ArrayList() { userName, roleId, identificationNumber, login, paging.PageNumber, paging.PageSize};
            //DataTable dt = DataAccessComponent.ExecuteSelect("procUsersByFilterSelect", parameters);
            //return ReadTable(dt) as UserCollection;

            ArrayList parameters = new ArrayList() { userName, roleId, identificationNumber, login, paging.PageNumber, paging.PageSize };
            
            try
            {
                DataSet ds = DataAccessComponent.ExecuteMultipleSelect("procUsersByFilterSelect", parameters);
                UserCollection result = null;
                if (ds.Tables.Count == 2)
                {
                    result = ReadTable(ds.Tables[0]) as UserCollection;
                    if (ds.Tables[1].Rows.Count > 0)
                    {
                        result.TotalResults = (int)ds.Tables[1].Rows[0][0];
                    }
                }
                return result;
            }
            catch (Exception ex)
            {

                throw;
            }
            
        }

        public void ChangePassword(User user)
        {
            ArrayList parameters = new ArrayList() { user.UserID, user.Password, user.MustChangePassword };
            DataAccessComponent.ExecuteOperation("procUsersChangePassword", parameters);
        }

        public void UpdateInvalidLoginAttempts(User user)
        {
            var parameters = new ArrayList() { user.UserID, user.LoginAttempts, user.Status };
            DataAccessComponent.ExecuteOperation("procUsersLoginAttemptsUpdate", parameters);
        }
    }
}
